package com.wechat.scheme.handler;

import cn.hutool.core.collection.CollectionUtil;
import com.wechat.scheme.builder.TextBuilder;
import com.wechat.scheme.constant.GlobalConstant;
import com.wechat.scheme.entity.BaiduSource;
import com.wechat.scheme.entity.WxMsg;
import com.wechat.scheme.repo.BaiduSourceRepo;
import com.wechat.scheme.repo.WxMsgRepo;
import com.wechat.scheme.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 */
@Slf4j
@Component
public class MsgHandler extends AbstractHandler {

    @Autowired
    private BaiduSourceRepo baiduSourceRepo;

    @Autowired
    WxMsgRepo wxMsgRepo;

    private static final String temple_str = "请检查名字是否正确\n" +
            "---------------\n" +
            "例如：王国<第二季>，则只需回复王国第二季即可\n" +
            "---------------\n" +
            "如正确，则暂未添加，我们将尽快更新";

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地

        }
        String respContent = "";

        try {
            //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服 todo
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                && weixinService.getKefuService().kfOnlineList()
                .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser()).build();
            }
            //check 搜索资源
            String content = StringUtils.isEmpty(wxMessage.getContent()) ? "" : wxMessage.getContent().trim();
            WxMsg msg = WxMsg.builder()
                    .content(content)
                    .fromUserName(wxMessage.getFromUser())
                    .toUserName(wxMessage.getToUser())
                    .msgType(wxMessage.getMsgType())
                    .msgJson(wxMessage.toString()).build();
            if(content.contains("-")) {
                String[] strs = content.split("-");
                if (strs[0].equalsIgnoreCase(GlobalConstant.ReplyKeyWord.TEXT_FRE_MV.code)
                        || strs[0].equalsIgnoreCase(GlobalConstant.ReplyKeyWord.TEXT_FRE_TB.code)) {
                    msg.setType(strs[0].toUpperCase());
                    List<BaiduSource> queryList = baiduSourceRepo.findByKeyWordLike(strs[1]);
                    ;
                    if (CollectionUtil.isNotEmpty(queryList)) {
                        respContent = "已为小主马不停蹄找到资源:" + "\n";
                        respContent += queryList.stream().map(p -> p.getKeyWord() + "->" + p.getUrlAddr()).collect(Collectors.joining("\n"));
                        log.info(respContent);
                    } else {
                        respContent = temple_str;
                    }
                } else if (content.startsWith(GlobalConstant.ReplyKeyWord.TEXT_FRE_SK.code)) {
                    //求资源
                    msg.setType((GlobalConstant.ReplyKeyWord.TEXT_FRE_SK.code));
                    respContent = GlobalConstant.ReplyKeyWord.TEXT_FRE_SK.value;
                }else{
                    msg.setType((GlobalConstant.ReplyKeyWord.TEXT_FRE_UNKOWN.code));
                    respContent = GlobalConstant.ReplyKeyWord.TEXT_FRE_UNKOWN.value;
                }
            }else{
                msg.setType((GlobalConstant.ReplyKeyWord.TEXT_FRE_UNKOWN.code));
                respContent = GlobalConstant.ReplyKeyWord.TEXT_FRE_UNKOWN.value;
            }
            wxMsgRepo.save(msg);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return new TextBuilder().build(respContent, wxMessage, weixinService);

    }

}
